#!/bin/sh

#simple script to transcode all files in a directory to OGG while moving transcoded files to an "archive" directory

BASE_DIR=/var/www/videosite
MEDIA_DIR=$BASE_DIR/media
ARCHIVE_DIR=$MEDIA_DIR/archive
PROCESSING_DIR=$MEDIA_DIR/processing
UPLOADS_DIR=$MEDIA_DIR/uploads
TRANSCODED_DIR=$MEDIA_DIR/transcoded

DB_FILE=$BASE_DIR/data/db.sqlite

VLC=/usr/bin/vlc

cd ${UPLOADS_DIR}

#XXX TODO: check for errors processing the file
#XXX TODO: check for valid extensions
#XXX TODO: generate random destination file name so we don't overwrite

for INPUT in `find $UPLOADS_DIR -type f -atime -1 -name '*.*' | sed 's_.*/__'` ; do
  echo "Processing $INPUT"
  INPUT_BASE=`echo ${INPUT%\.*}`
  INPUT_EXT=`echo $INPUT | sed 's/.*\.//'`
  OUTPUT_BASE=`md5sum $UPLOADS_DIR/$INPUT | awk '{ print $1 }'`
  mv $UPLOADS_DIR/$INPUT $PROCESSING_DIR/$OUTPUT_BASE.$INPUT_EXT
  $VLC -vvv "$PROCESSING_DIR/$OUTPUT_BASE.$INPUT_EXT" --sout "#transcode{vcodec=theora,acodec=vorbis,vb=800,ab=96}:duplicate{dst=std{access=file,mux=ogg,dst=${TRANSCODED_DIR}/${OUTPUT_BASE}.ogg}}" vlc://quit -I dummy
  mv $PROCESSING_DIR/$OUTPUT_BASE.$INPUT_EXT $ARCHIVE_DIR/$OUTPUT_BASE.$INPUT_EXT
  sqlite $DB_FILE "update videos set filename = '${OUTPUT_BASE}.${INPUT_EXT}' where filename = '${INPUT}'"
done

echo "done"
